<template>
  <view class="content" style="background: transparent;">
    <view class="bott-btn">
      <button type="primary" @click="handleClick">确认</button>
    </view>
    <view class="phxx-item-detail">
      <view class="content-box">
        <view class="bottom block-back">
          <view class="uni-form-item">
            <view class="title"><span style="color: red">*</span>供应商名称</view>
            <input class="uni-input" v-model="itemList.cusName" maxlength="50" minlength="1" />
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color: red">*</span>供应商简称</view>
            <input class="uni-input" v-model="itemList.supplierAbbreviation" maxlength="50" minlength="1" />
          </view>
          <view v-if="isShowERP && isEditType === 'add'" class="uni-form-item">
            <view class="title"><span style="color: red">*</span>ERP供应商</view>
            <view class="uni-select-box">
              <picker :disabled="isDisabled" @change="changeTrader" :value="itemList.traderName" mode="selector"
                :range="traderList" range-key="traderName">
                <view v-if="itemList.traderName" class="uni-input">{{ itemList.traderName || '' }}</view>
                <view v-else class="placeholder">请选择ERP供应商</view>
              </picker>
              <uni-icons type="forward" size="20"></uni-icons>
            </view>
          </view>
          <view v-if="isShowERP && isEditType === 'update'" class="uni-form-item">
            <view class="title"><span style="color: red">*</span>ERP供应商</view>
            <view class="uni-select-box">
              <input class="uni-input" :disabled="isEditType === 'update'" v-model="itemList.traderName" maxlength="50"
                minlength="1" />
            </view>
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color: red">*</span>统一社会信用代码</view>
            <input class="uni-input" v-model="itemList.cusSocial" maxlength="50" minlength="1" />
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color: red">*</span>联系人</view>
            <input class="uni-input" v-model="itemList.contactPerson" maxlength="20" minlength="1" />
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color: red">*</span>联系电话</view>
            <input class="uni-input" v-model="itemList.cusPhone" maxlength="11" minlength="1" />
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color: red">*</span>企业类别</view>
            <view class="uni-select-box">
              <picker :disabled="isDisabled" @change="changeCompany" :value="itemList.cusType" mode="selector"
                :range="companyRange" range-key="label">
                <view class="uni-input">{{ cusTypeName || '' }}</view>
              </picker>
              <uni-icons type="forward" size="20"></uni-icons>
            </view>
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color: red">*</span>结算类型</view>
            <view class="uni-select-box">
              <picker :disabled="isDisabled" @change="changeSettle" :value="itemList.settlementNodeCode" mode="selector"
                :range="settleRange" range-key="label">
                <view class="uni-input">{{ settleName || '' }}</view>
              </picker>
              <uni-icons type="forward" size="20"></uni-icons>
            </view>
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color: red">*</span>省</view>
            <view class="uni-select-box">
              <picker :disabled="isDisabled" @change="changeProvince" :value="itemList.cusProvince" mode="selector"
                :range="provinceLists" range-key="text">
                <view class="uni-input">{{ provinceName || '' }}</view>
              </picker>
              <uni-icons type="forward" size="20"></uni-icons>
            </view>
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color: red">*</span>市</view>
            <view class="uni-select-box">
              <picker :disabled="isDisabled" @change="changeCity" :value="itemList.cusCity" mode="selector"
                :range="cityLists" range-key="text">
                <view class="uni-input">{{ cityName || '' }}</view>
              </picker>
              <uni-icons type="forward" size="20"></uni-icons>
            </view>
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color: red">*</span>区县</view>
            <view class="uni-select-box">
              <picker :disabled="isDisabled" @change="changeCuontry" :value="itemList.cusCounty" mode="selector"
                :range="cuontryLists" range-key="text">
                <view class="uni-input">{{ countyName || '' }}</view>
              </picker>
              <uni-icons type="forward" size="20"></uni-icons>
            </view>
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color: red">*</span>街道</view>
            <view class="uni-select-box">
              <picker :disabled="isDisabled" @change="changeTown" :value="itemList.cusTown" mode="selector"
                :range="townLists" range-key="text">
                <view class="uni-input">{{ townName || '' }}</view>
              </picker>
              <uni-icons type="forward" size="20"></uni-icons>
            </view>
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color: red">*</span>详细地址</view>
            <input class="uni-input" v-model="itemList.regAddress" @input="changeRegdd" maxlength="50" minlength="1" />
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import { toast } from '@/utils/common';
  import { getTenantId } from '@/utils/auth';
  import { getAreaTrees } from '@/api/address.js';
  import { getBasisDeploy } from "@/api/system/user.js"
  import { createOne, updateOne, getDetails, reportSupplier, getErpSupplierList } from '@/api/supplier.js';
  import { getDictList } from '@/api/login';
  export default {
    driverName: 'resetPwd',
    props: {},
    data() {
      return {
        isShowERP: false,
        provinceName: '',
        isDisabled: false,
        cusTypeName: '',
        cityName: '',
        countyName: '',
        townName: '',
        provinceLists: [],
        cityLists: [],
        cuontryLists: [],
        townLists: [],
        companyRange: [],
        traderList: [],
        settleName: '',
        settleRange: [
          {
            label: '出矿过重',
            value: 1
          },
          {
            label: '入厂过重',
            value: 2
          }
        ],
        itemList: {
          id: undefined,
          cusName: undefined,
          traderNo: undefined,
          traderName: undefined,
          cusProvinceName: undefined,
          cusCityName: undefined,
          supplierAbbreviation: undefined,
          cusSocial: undefined,
          cusPhone: undefined,
          cusProvince: undefined,
          cusCity: undefined,
          cusCounty: undefined,
          cusTown: undefined,
          regAddress: undefined,
          address: undefined,
          contactPerson: undefined,
          enterId: undefined,
          userId: undefined,
          cusType: undefined
        },
        isFirst: true,
        tempDatas: {},
        isEdit: false,
        fromMap: false,
        ifFirstEdit: true,
        isEditType: 'add'
      };
    },
    async onLoad(options) {
      this.getDictLists();
      await this.getBasisDeploy();
      if (this.isShowERP) {
        this.getErpSupplierList()
      }
      this.fromMap = false;
      if (!!options) {
        this.isEdit = true;
        if (!!options.id) {

          this.isEditType = 'update';
          this.getDetail(options.id);
        } else this.isEdit = false;
      }
      if (!this.isEdit) {
        uni.setNavigationBarTitle({
          title: '添加'
        });
      } else {
        uni.setNavigationBarTitle({
          title: '编辑'
        });
      }
      this.getProvinces();
    },
    watch: {
      'itemList.cusProvince': function (newVal, oldVal) {
        if (!this.ifFirstEdit) {
          this.itemList.cusCity = undefined;
          this.itemList.cusCounty = undefined;
          this.itemList.cusTown = undefined;
          this.$set(this, 'cityName', '');
          this.$set(this, 'countyName', '');
          this.$set(this, 'townName', '');
        }

        if (!!newVal) this.getCitys(newVal);
      },
      'itemList.cusCity': function (newVal, oldVal) {
        if (!this.ifFirstEdit) {
          this.itemList.cusCounty = undefined;
          this.itemList.cusTown = undefined;
          this.$set(this, 'countyName', '');
          this.$set(this, 'townName', '');
        }
        if (!!newVal) this.getCountys(newVal);
      },
      'itemList.cusCounty': function (newVal, oldVal) {
        if (!this.ifFirstEdit) {
          this.itemList.cusTown = undefined;
          this.$set(this, 'townName', '');
        }

        if (!!newVal) this.getTowns(newVal);
      }
    },
    methods: {
      async getBasisDeploy() {
        const res = await getBasisDeploy(getTenantId())
        if (res.code === '200') {
          this.isShowERP = res.data?.erpDocking === 0
        } else {
          toast(res.msg)
        }
      },
      async getErpSupplierList() {
        const res = await getErpSupplierList()
        if (res.code === 0) {
          this.traderList = res.data || []
        }
      },
      async getDictLists() {
        const res = await getDictList();
        if (res.code === 0) {
          this.companyRange = (res?.data || []).filter(
            (e) => e.dictType === 'enter_type'
          );
          this.cusTypeName = this.companyRange[0].label;
          this.itemList.cusType = this.companyRange[0].value;
        }
      },
      async getDetail(id) {
        this.ifFirstEdit = true;
        let data = await getDetails(id);
        let _ = this;
        if (data.code == 0) {
          _.tempDatas = data.data;
          this.getProvinces(data.data.cusProvince);
          this.getCitys(data.data.cusProvince, data.data.cusCity);
          this.getCountys(data.data.cusCity, data.data.cusCounty);
          this.getTowns(data.data.cusCounty, data.data.cusTown);
          if (data.data.settlementNodeCode == 1) {
            _.settleName = '出矿过重';
          } else if (data.data.settlementNodeCode == 2) {
            _.settleName = '入厂过重';
          }
          _.itemList.settlementNodeCode = data.data.settlementNodeCode;
          _.itemList.id = data.data.id;
          _.itemList.cusName = data.data.cusName;
          _.itemList.traderNo = data.data.traderNo;
          _.itemList.traderName = data.data.traderName;
          _.itemList.supplierAbbreviation = data.data.supplierAbbreviation;
          _.itemList.cusSocial = data.data.cusSocial;
          _.itemList.cusPhone = data.data.cusPhone;
          _.itemList.cusType = data.data.cusType;
          _.itemList.address = data.data.address;
          _.itemList.cusProvince = data.data.cusProvince;
          _.itemList.cusCity = data.data.cusCity;
          _.itemList.cusCounty = data.data.cusCounty;
          _.itemList.contactPerson = data.data.contactPerson;
          _.itemList.cusTown = data.data.cusTown;
          _.itemList.regAddress = data.data.regAddress;
        }
      },
      async getProvinces(...curId) {
        let data = await getAreaTrees(0);
        if (!!data) {
          if (!!data.data && data.data.length > 0) {
            this.provinceLists = [];
            data.data.forEach((item) => {
              this.provinceLists.push({
                value: item.id,
                text: item.name
              });
              this.provinceLists.forEach((item) => {
                if (item.value == curId) {
                  this.provinceName = item.text;
                }
              });
            });
          }
        }
      },
      async getCitys(id, curId) {
        let data = await getAreaTrees(id);
        if (!!data && data.data.length > 0) {
          this.cityLists = [];
          data.data.forEach((item) => {
            this.cityLists.push({
              value: item.id,
              text: item.name
            });
            this.cityLists.forEach((item) => {
              if (item.value == curId) {
                this.cityName = item.text;
              }
            });
          });
        }
      },
      async getCountys(id, curId) {
        let data = await getAreaTrees(id);
        if (!!data && data.data.length > 0) {
          this.cuontryLists = [];
          data.data.forEach((item) => {
            this.cuontryLists.push({
              value: item.id,
              text: item.name
            });
            this.cuontryLists.forEach((item) => {
              if (item.value == curId) {
                this.countyName = item.text;
              }
            });
          });
        }
      },
      async getTowns(id, curId) {
        let data = await getAreaTrees(id);
        if (!!data && data.data.length > 0) {
          this.townLists = [];
          data.data.forEach((item) => {
            this.townLists.push({
              value: item.id,
              text: item.name
            });
            this.townLists.forEach((item) => {
              if (item.value == curId) {
                this.townName = item.text;
              }
            });
          });
        }
      },
      changeProvince(e) {
        this.ifFirstEdit = false;
        if (this.provinceLists.length > 0) {
          this.provinceName = this.provinceLists[e.detail.value].text;
          this.itemList.cusProvince = this.provinceLists[e.detail.value].value;
        }

        this.adressFun();
      },
      changeCity(e) {
        this.ifFirstEdit = false;
        this.itemList.city = e;
        if (this.cityLists.length > 0) {
          this.cityName = this.cityLists[e.detail.value].text;
          this.itemList.cusCity = this.cityLists[e.detail.value].value;
        }
        this.adressFun();
      },
      changeCuontry(e) {
        this.ifFirstEdit = false;
        if (this.cuontryLists.length > 0) {
          this.countyName = this.cuontryLists[e.detail.value].text;
          this.itemList.cusCounty = this.cuontryLists[e.detail.value].value;
        }
        this.adressFun();
      },
      changeTown(e) {
        this.ifFirstEdit = false;
        if (this.townLists.length > 0) {
          this.townName = this.townLists[e.detail.value].text;
          this.itemList.cusTown = this.townLists[e.detail.value].value;
        }
        this.adressFun();
      },
      changeRegdd() {
        this.adressFun();
      },
      adressFun() {
        if (
          !!this.provinceName &&
          !!this.cityName &&
          !!this.countyName &&
          !!this.townName &&
          !!this.itemList.regAddress
        ) {
          this.itemList.address =
            this.provinceName +
            this.cityName +
            this.countyName +
            this.townName +
            this.itemList.regAddress;
        }
      },
      changeTrader(value) {
        const index = value.detail.value;
        const data = this.traderList[index];
        this.itemList.traderNo = data?.traderNo;
        this.itemList.traderName = data?.traderName;
        this.itemList.cusSocial = data?.traderSocial;
      },
      changeCompany(e) {
        if (this.companyRange.length > 0) {
          this.cusTypeName = this.companyRange[e.detail.value].label;
          this.itemList.cusType = this.companyRange[e.detail.value].value;
        }
      },
      changeSettle(e) {
        this.settleName = this.settleRange[e.detail.value].label;
        this.itemList.settlementNodeCode = this.settleRange[e.detail.value].value;
      },
      chooseAdress() {
        let _this = this;
        wx.chooseLocation({
          success: (res) => {
            console.log(res, '这是获取到的地理位置');
            this.itemList.cusProvince = undefined;
            this.itemList.provinceName = undefined;
            this.itemList.city = undefined;
            this.itemList.county = undefined;
            this.itemList.town = undefined;
            this.itemList.cityName = undefined;
            this.itemList.countyName = undefined;
            this.itemList.townName = undefined;
            this.itemList.address = res.address;
            this.fromMap = true;
          },
          fail: (err) => {
            console.log(err);
          }
        });
      },
      async handleClick() {
        let data = {};
        let _ = this;
        if (!_.itemList.cusName) {
          toast(`供应商名称不能为空`);
          return;
        }
        if (!_.itemList.supplierAbbreviation) {
          toast(`供应商简称不能为空`);
          return;
        }
        if (this.isShowERP) {
          if (!this.itemList.traderNo) {
            toast(`ERP供应商不能为空`);
            return;
          }
        }
        if (!_.itemList.cusSocial) {
          toast(`统一社会信用代码不能为空`);
          return;
        }
        if (!_.itemList.settlementNodeCode) {
          toast(`结算类型不能为空`);
          return;
        }
        if (!_.itemList.contactPerson) {
          toast(`联系人不能为空`);
          return;
        }
        if (!_.itemList.cusPhone) {
          toast(`联系电话不能为空`);
          return;
        }
        if (!_.itemList.cusProvince) {
          toast(`省不能为空`);
          return;
        }
        if (!_.itemList.cusCity) {
          toast(`市不能为空`);
          return;
        }
        if (!_.itemList.cusCounty) {
          toast(`区县不能为空`);
          return;
        }
        if (!_.itemList.cusTown) {
          toast(`街道不能为空`);
          return;
        }
        if (!_.itemList.regAddress) {
          toast(`详细地址不能为空`);
          return;
        }


        this.itemList.cusProvinceName = this.provinceName
        this.itemList.cusCityName = this.cityName
        let msg = '';
        if (this.isEditType == 'update') {
          msg = '编辑';
          data = await updateOne(this.itemList);
        } else {
          msg = '添加';
          data = await createOne(this.itemList);
        }
        if (data.code == 0) {
          uni.showToast({
            title: msg + '成功',
            icon: 'success'
          });
          //添加完后，上报
          if (this.isEditType == 'add') {
            reportSupplier(data.data);
          }
          setTimeout(() => {
            wx.navigateBack({
              delta: 1,
            });
          }, 20);

        } else {
          toast(data.msg);
        }
      },
      parseTime(time, pattern) {
        if (arguments.length === 0 || !time) {
          return null;
        }
        const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
        let date;
        if (typeof time === 'object') {
          date = time;
        } else {
          if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
            time = parseInt(time);
          } else if (typeof time === 'string') {
            time = time
              .replace(new RegExp(/-/gm), '/')
              .replace('T', ' ')
              .replace(new RegExp(/\.[\d]{3}/gm), '');
          }
          if (typeof time === 'number' && time.toString().length === 10) {
            time = time * 1000;
          }
          date = new Date(time);
        }
        const formatObj = {
          y: date.getFullYear(),
          m: date.getMonth() + 1,
          d: date.getDate(),
          h: date.getHours(),
          i: date.getMinutes(),
          s: date.getSeconds(),
          a: date.getDay()
        };
        const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
          let value = formatObj[key];
          // Note: getDay() returns 0 on Sunday
          if (key === 'a') {
            return ['日', '一', '二', '三', '四', '五', '六'][value];
          }
          if (result.length > 0 && value < 10) {
            value = '0' + value;
          }
          return value || 0;
        });
        return time_str;
      }
    }
  };
</script>

<style lang="scss" scoped>
  .uni-form-item {
    border-bottom: 1px solid #E6E6E6;
    display: flex;
    justify-content: space-between;
    line-height: 100rpx;
    height: 100rpx;
    color: #333;

    .title {
      width: 218rpx;
    }

    .uni-input {
      flex: 3;
      border: 1px solid #fff;
      height: 70rpx;
      line-height: 70rpx;
      border-radius: 10rpx;
      padding: 0 10rpx;
      background-color: #fff;
      bottom: -14rpx;
      position: relative;
    }

    .uni-select-box {
      width: calc(100% - 186rpx);
      display: flex;
      justify-content: space-between;
      background: #fff;

      picker {
        width: 100%;
      }
    }
  }

  .phxx-item-detail {
    box-sizing: border-box;
    font-size: 14px;
    color: #000;
    margin: 20rpx;

    .content-box {
      .bottom {
        padding: 20rpx;
        font-size: 26.66rpx;
      }

      .btns {
        position: fixed;
        bottom: 0;
        height: 150rpx;
        width: 100%;
        margin: auto;
        z-index: 99;
        left: 0;
        right: 0;
        background-color: #fff;
      }
    }
  }

  .uni-input {
    color: #000;
  }
</style>